package com.imay.live.fragment.room;

import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.imay.base.fragment.BaseDialogFragment;
import com.imay.base.util.FileUtil;
import com.imay.live.Constants;
import com.imay.live.activity.dynamics.ReleaseActivity;
import com.imay.live.helper.FileHelper;
import com.imay.live.media.LivePlayer;
import com.imay.live.utils.ToastUtil;
import com.imay.live.R;
import com.tencent.rtmp.ITXLivePlayListener;
import com.tencent.rtmp.TXLiveConstants;
import com.tencent.rtmp.ugc.TXRecordCommon;
import com.tencent.rtmp.ui.TXCloudVideoView;

import java.io.File;

/**
 * Created by jeaman on 2017/5/24.
 */

public class LiveRecordFragment extends BaseDialogFragment implements View.OnClickListener, View.OnLongClickListener, ITXLivePlayListener {
    private final static int MAX_SECONDS = 60;
    private final static int MIN_SECONDS = 3;
    private ProgressBar mProgressBar;
    private View mStartView;
    private TextView mTimeTv;

    private boolean mStarted;

    private long mRecordMilliSecond;   //录制时间
    private boolean mCancelRecord;

    private TXCloudVideoView mVideoView;

    private LivePlayer mLivePlayer;
    private String mVideoPath;
    private String mCoverPath;
    private boolean mPublish;   //是否发布，发布则不删除源文件
    private long mStartRecordTime;

    public static LiveRecordFragment newInstance() {
        return new LiveRecordFragment();
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_live_record;
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        setCancelable(false);

        mProgressBar = $(R.id.live_record_pb_progress);
        mTimeTv = $(R.id.live_record_tv_time);
        mStartView = $(R.id.live_record_iv_record);

        $(R.id.live_record_tv_cancel).setOnClickListener(this);

        mProgressBar.setMax(MAX_SECONDS);
        mProgressBar.setSecondaryProgress(MIN_SECONDS);
        mStartView.setOnClickListener(this);
        mStartView.setOnLongClickListener(this);

        reset();
    }

    private void initPreview(String videoPath, String coverPath) {
        $(R.id.live_record_rl_record).setVisibility(View.GONE);
        $(R.id.live_record_rl_preview).setVisibility(View.VISIBLE);

        mVideoView = $(R.id.live_record_preview_vv_video);

        $(R.id.live_record_preview_iv_close).setOnClickListener(this);
        $(R.id.live_record_preview_btn_save).setOnClickListener(this);
        $(R.id.live_record_preview_btn_share).setOnClickListener(this);

        mLivePlayer = new LivePlayer(getActivity(), mVideoView);

        mVideoPath = videoPath;
        mCoverPath = coverPath;
        startPlay();
    }

    @Override
    protected boolean isMatchParent() {
        return true;
    }

    @Override
    protected int getHeight() {
        return ViewGroup.LayoutParams.WRAP_CONTENT;
    }

    @Override
    protected int getGravity() {
        return Gravity.BOTTOM;
    }

    @Override
    protected boolean isTranslucentBackground() {
        return true;
    }

    private void startPlay() {
        mLivePlayer.setLocalUrl(mVideoPath);
        mLivePlayer.startPlay(this);
        mLivePlayer.setMute(true);
    }

    private void saveVideo() {
        String videoPath = FileHelper.getInstance().getImageFile().getAbsolutePath();
        if (FileUtil.moveFile(mVideoPath, videoPath)) {
            //dismiss();
            mPublish = true;
            String path = videoPath + File.separator +
                    mVideoPath.substring(mVideoPath.lastIndexOf("/") + 1);
            mVideoPath = path;
            try {
                File file = new File(mVideoPath);
                if (file.exists()) {
                    getActivity().sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(file)));
                }
            } catch (Exception e) {

            }
            ToastUtil.show(getActivity(), R.string.live_record_save_success);
        } else {
            ToastUtil.show(getActivity(), R.string.live_record_save_failed);
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        if (mLivePlayer != null) {
            mLivePlayer.pause();
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        if (mLivePlayer != null) {
            mLivePlayer.resume();
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.live_record_tv_cancel:
                onCancelRecordClick();
                dismiss();
                break;
            case R.id.live_record_iv_record:
                if (mStarted) {
                    onStopRecordClick();
                } else {
                    startRecord();
                }
                break;
            case R.id.live_record_preview_iv_close: //关闭
                dismiss();
                break;
            case R.id.live_record_preview_btn_save: //保存
                saveVideo();
                break;
            case R.id.live_record_preview_btn_share:    //发布
                mPublish = true;
                ReleaseActivity.startActivity(getActivity(), mCoverPath, mVideoPath, null, ReleaseActivity.MOVIE, false, Constants.DYNAMICSFEED_REQUEST_CODE);
                dismiss();
                break;
        }
    }

    @Override
    public boolean onLongClick(View v) {
        startRecord();
        return false;
    }

    @Override
    public void onDismiss(DialogInterface dialog) {
        if (mStarted) {
            onCancelRecordClick();
        }
        if (mLivePlayer != null) {
            mLivePlayer.onDestroy();
        }
        if (!mPublish) {
            deleteFile(mVideoPath, mCoverPath);
        }
        super.onDismiss(dialog);
    }

    private void startRecord() {
        if (!mStarted) {
            mRecordMilliSecond = 0;
            mStartRecordTime = System.currentTimeMillis();  //作为每次录制的回调
            final long startRecordIndex = mStartRecordTime;
            LivePlayer livePlayer = getLivePlayer();
            if (livePlayer != null) {
                int result = livePlayer.startRecord(new TXRecordCommon.ITXVideoRecordListener() {
                    @Override
                    public void onRecordEvent(int i, Bundle bundle) {

                    }

                    @Override
                    public void onRecordProgress(long milliSecond) {
                        if (startRecordIndex == mStartRecordTime && !mCancelRecord) {
                            mRecordMilliSecond = milliSecond;
                            setProgress(milliSecond);
                        }
                    }

                    @Override
                    public void onRecordComplete(TXRecordCommon.TXRecordResult result) {
                        if (startRecordIndex == mStartRecordTime && !mCancelRecord) {
                            if (result.retCode == TXRecordCommon.RECORD_RESULT_OK) {
                                if (isAdded() && !isTooShort()) {
                                    initPreview(result.videoPath, result.coverPath);
                                } else {
                                    deleteFile(result.videoPath, result.coverPath);
                                }
                            } else {
                                if (isAdded()) {
                                    ToastUtil.show(getActivity(), getString(R.string.live_record_failed, result.descMsg));
                                }
                            }
                        } else {
                            deleteFile(result.videoPath, result.coverPath);
                        }
                    }
                });
                if (result < 0) {
                    ToastUtil.show(getActivity(), getString(R.string.live_record_no_stream));
                } else {
                    mStarted = true;
                    mStartView.setSelected(true);
                }
            }
        }
    }

    private void onStopRecordClick() {
        //录制时间小于3秒
        if (isTooShort()) {
            ToastUtil.show(getActivity(), getString(R.string.live_record_too_short, MIN_SECONDS));
            mStartRecordTime = 0;   //忽略当前录制结果
        }
        stopRecord();
    }

    private boolean isTooShort() {
        return mRecordMilliSecond < MIN_SECONDS * 1000;
    }

    private void onCancelRecordClick() {
        mCancelRecord = true;
        stopRecord();
    }

    private void stopRecord() {
        mStarted = false;
        LivePlayer livePlayer = getLivePlayer();
        if (livePlayer != null) {
            livePlayer.stopRecord();
        }
        reset();
    }

    private void setProgress(long milliSecond) {
        int progress = (int) (milliSecond / 1000);
        if (progress >= MAX_SECONDS) {
            stopRecord();
        }
        if (isAdded()) {
            mProgressBar.setProgress(progress);
            mTimeTv.setText(getResources().getString(R.string.live_record_time, MAX_SECONDS - progress));
        }
    }

    private void reset() {
        if (isAdded()) {
            mProgressBar.setProgress(0);
            mTimeTv.setText(getResources().getString(R.string.live_record_time, MAX_SECONDS));
            mStartView.setSelected(false);
        }
        mStarted = false;
    }

    private LivePlayer getLivePlayer() {
        if (getActivity() instanceof OnLiveRecordListener) {
            return ((OnLiveRecordListener) getActivity()).getLivePlayer();
        }
        return null;
    }

    private void deleteFile(String videoPath, String coverPath) {
        FileUtil.deleteFile(videoPath);
        FileUtil.deleteFile(coverPath);
    }

    @Override
    public void onPlayEvent(int event, Bundle bundle) {
        if (event == TXLiveConstants.PLAY_EVT_PLAY_END) {   //循环播放
            startPlay();
        }

    }

    @Override
    public void onNetStatus(Bundle bundle) {

    }

    public interface OnLiveRecordListener {
        LivePlayer getLivePlayer();
    }
}
